using System;
using CodePlex.TfsLibrary.ObjectModel;
using CodePlex.TfsLibrary.RepositoryWebSvc;

namespace CodePlex.CodePlexClientLibrary
{
    [Command("log", "shows history for a file or directory", MinArgs = 1, UsageSummary = "<path...> [options]", UsageDescription = "Prints the history for a file or directory in the source control system.")]
    public class LogCommand : AuthenticatedCommand
    {
        bool quiet;

        [Option("quiet", "do not print commit messages", ShortName = "q")]
        public bool Quiet
        {
            get { return quiet; }
            set { quiet = value; }
        }

        public override void Execute()
        {
            foreach (string path in Arguments)
                Engine.Log(CodePlexClientUtil.GetFullPath(path), VersionSpec.First, VersionSpec.Latest, 256, OnLogItem);

            Console.WriteLine("========================================================================");
        }

        void OnLogItem(LogItem item,
                       SourceItemResult result)
        {
            Console.WriteLine("========================================================================");

            if (result != SourceItemResult.S_Ok)
                ConsoleUtil.PrintCommandError(item.LocalPath, result);
            else
            {
                Console.WriteLine("Log for {0}", item.ServerPath);

                foreach (SourceItemHistory history in item.History)
                {
                    Console.WriteLine("------------------------------------------------------------------------");
                    Console.WriteLine("r{0} | {1} | {2} {3}", history.ChangeSetID, history.Username,
                                      history.CommitDateTime.ToShortDateString(), history.CommitDateTime.ToShortTimeString());

                    if (!Quiet)
                    {
                        Console.WriteLine();
                        Console.WriteLine(history.Comment);
                    }
                }
            }
        }
    }
}